package com.lagou.edu.tpmonitor.model;

import org.springframework.util.Assert;

/**
 * 执行时间监控对象
 *
 * @author liangzj
 * @date 2021/5/22 9:03
 */
public class TimeMonitor implements Comparable<TimeMonitor> {

    private static final String STATUS_INIT = "init";
    private static final String STATUS_RUNNING = "running";
    private static final String STATUS_FINISH = "finish";

    /**
     * 开始执行时间
     */
    private Long startTime;

    /**
     * 结束执行时间
     */
    private Long endTime;

    /**
     * 执行时间
     */
    private Long runningTime;

    /**
     * 执行状态
     */
    private String status = STATUS_INIT;

    public void start() {
        Assert.isTrue(STATUS_INIT.equals(status), "not init");
        startTime = System.currentTimeMillis();
        status = STATUS_RUNNING;
    }

    public void stop() {
        Assert.isTrue(STATUS_RUNNING.equals(status), "not running");
        endTime = System.currentTimeMillis();
        runningTime = endTime - startTime;
        status = STATUS_FINISH;
    }

    public Long getRunningTime() {
        Assert.isTrue(STATUS_FINISH.equals(status), "not finish");
        return runningTime;
    }

    public Long getStartTime() {
        return startTime;
    }

    public String getStatus() {
        return status;
    }

    @Override
    public int compareTo(TimeMonitor o) {
        Assert.isTrue(STATUS_FINISH.equals(status) && STATUS_FINISH.equals(o.status),
                "can not compare unfinished record");
        return (int) (this.runningTime - o.runningTime);
    }

}
